<?php

namespace app\platform\controller\account;

use app\BaseController;

use app\common\logic\AppLogic;

use app\common\logic\CreateShopLogic;

use app\common\logic\TokenLogic;

use app\common\model\account\AccountModel;

use app\common\model\account\ShopAccountModel;

use app\common\model\AppModel;

use app\common\model\ShopModel;

use app\common\model\TokenModel;

use app\common\helper\sms\SmsHelper;

class Main extends BaseController{



    public function pwdLogin(){

        $mobile = $this->request->param('mobile');

        $pwd    = $this->request->param('pwd');

        if (empty($mobile) || !is_mobile($mobile)) {

            return $this->error('手机号码不能为空');

        }

        if(empty($pwd)){

            return $this->error('密码不能为空');

        }

        if (null === $account = AccountModel::where([['mobile','=',$mobile],['is_delete','=',0]])->find()) {

            return $this->error('账号或密码错误');

        }

        if(empty($account->password)){

            return $this->error('该账号暂不支持密码登录');

        }
        if($account->password != md5($pwd)){

            return $this->error('账号或密码错误');

        }

        $account->code=rand(111111,999999);

        $account->last_login_time = $this->request->time();

        $account->save();

        $auth_token = TokenLogic::getAccountToken($account->account_id,$account->code);

        return $this->success([

            'auth_token' => $auth_token

        ]);

    }

    

    public function login()

    {

        $mobile = $this->request->param('mobile');

        $code = $this->request->param('code');

        $token = $this->request->param('token');

        if (empty($mobile) || !is_mobile($mobile)) {

            return $this->error('手机号码不能为空');

        }

        if (empty($code)) {

            return $this->error('验证码不能为空');

        }

        if (empty($token)) {

            return $this->error('令牌不存在或者已过期');

        }

        if (null === $datas = TokenModel::where('token', $token)->find()) {

            return $this->error('令牌不存在或者已过期');

        }

        if($datas->type != $this->request->type){

            return $this->error('令牌不存在或者已过期');

        }

        if (empty($datas['code'])) {

            return $this->error('验证码不正确');

        }

        if (empty($datas['mobile'])) {

            return $this->error('手机号码不正确');

        }

        if ($datas['mobile'] != $mobile || $datas['code'] != $code || $datas['add_ip'] != $this->request->ip()) {

            $datas->code_error_num = $datas->code_error_num + 1;

            $datas->save();

            return $this->error('验证码不正确');

        }

        if ($datas->code_error_num >= 3 || $datas->expire_time < $this->request->time()) { //一个验证码最多验证3次

            return $this->error('验证码已过期');

        }



        if (null === $account = AccountModel::where('mobile', $mobile)->find()) {

            $account = new AccountModel();

            $account->mobile = $mobile;

            $account->username=$mobile;

            $account->number=date("YmdHis").rand(111111,999999);

        }else{

            if($account->is_delete ==1){

                return $this->error('账号不存在');

            }

            if($account->status !=1){

                return $this->error('账号异常');

            }

        }



        $account->code=rand(111111,999999);

        $account->last_login_time = $this->request->time();

        $account->save();

        $auth_token = TokenLogic::getAccountToken($account->account_id,$account->code);

        $datas->delete();

        return $this->success([

            'auth_token' => $auth_token

        ]);

    }



    public function layout()

    {

        return $this->success([

            'account'=>$this->request->account

        ]);

    }



    public function editPwd(){

        $pwd = $this->request->param('pwd');

        $repwd = $this->request->param('repwd');

        if(empty($pwd) || empty($repwd)){

            return $this->error('密码和确认密码不能为空');

        }

        if(strlen($pwd) < 6){

            return $this->error('密码不能小于6位');

        }

        if($pwd != $repwd){

            return $this->error('两次密码输入不一致');

        }

        $this->request->account->password = md5($pwd);

        $this->request->account->save();

        return $this->success('设置成功');

    }

    

    public function home()

    {

        $mendian=ShopAccountModel::with(['shop'=>function($query){

            $query->with(['application']);

        }])->where([

            ['account_id','=',$this->request->accountId]

        ])->order(['add_time'=>'desc'])

            ->select()

            ->append(['add_time_format', 'shop_token'])

            ->toArray();



        return $this->success([

            'account'=>$this->request->account,

            'mendian'=>$mendian,

            'mendian_count'=>count($mendian),

        ]);

    }



    public function ShowApp()

    {

        $type=$this->request->param('type/d',1);

        $base_applications=AppModel::where([

            ['is_delete','=',0],

            ['type','=',1],
            ['app_id','<>',6]

        ])->order(['sort'=>'desc','add_time'=>'desc'])

            ->select()

            ->toArray();



        $type_list=AppLogic::getAppTypeList();



        $where=[

            ['is_delete','=',0],

        ];



        $where[]= $type==1 ? ['type','<>',1] : ['type','=',$type];
        $where[]=['app_id','<>',6];
        $applications=AppModel::where($where)

            ->order(['sort'=>'desc','add_time'=>'desc'])

            ->select()

            ->toArray();

        

        

        $ids = [];

        $apps = [];    

        foreach ($applications as $k =>$v){

            if(in_array($this->request->accountId,$v['white_list']) || $v['status'] == 1){

                $apps[] = $v;

                $ids[$v['type']] = $v['type'];

            }

        }

        $bases = [];

         foreach ($base_applications as $k =>$v){

            if(in_array($this->request->accountId,$v['white_list']) || $v['status'] == 1){

                $bases[] = $v;

            }

        }

        $showTypes = [];

        foreach($type_list as $val){

            if(isset($ids[$val['id']])){

                $showTypes[] = $val;

            }

        }



        $return=[

            'base_applications'=>$bases,

            'type_list'=>$showTypes,

            'applications'=>$apps,

        ];

        return $this->success($return);



    }





    public function getCode()

    {

        //CODE

        TokenModel::where([['expire_time', '<', $this->request->time()],['type','=',$this->request->type]])->delete();

        $code = md5(uniqid());

        $token = new TokenModel();

        $token->token = $code;

        $token->expire_time = $this->request->time() + 600;

        $token->type=$this->request->type;

        $token->save();

        return $this->success([

            'code' => $code,

        ]);

    }



    public function sms() { //短信不返回失败

        $token = $this->request->param('token');

        if (empty($token)) {

            return $this->success();

        }

        if (null === $data = TokenModel::find($token)) {

            return $this->success('1');

        }



        if ($data->type != $this->request->type) {

            return $this->success('2');

        }



        $mobile = $this->request->param('mobile');

        if (!is_mobile($mobile)) {

            return $this->success('3');

        }

        if (!empty($data['mobile']) && $data['mobile'] != $mobile) {

            return $this->success('4');

        }

        if ($data['expire_time'] < $this->request->time()) {

            return $this->success('5');

        }

        if ($data['add_ip'] != $this->request->ip()) {

            return $this->success('6');

        }

        $code = rand(100000, 999999);

        $data->code = $code;

        $data->mobile = $mobile;

        $data->code_error_num = 0;

        $data->expire_time = $this->request->time() + 600;

        $data->save();

//        $ret = sendMessage($mobile,$code,1);

        $SmsHelper = new SmsHelper();

        $SmsHelper->sendCode($mobile, $code);

        

        return $this->success('发送成功');

    }



    public function createShop()

    {

        $app_id=$this->request->param('app_id/d',0);

        $from_type = $this->request->param('from_type',1);

        $name=$this->request->param('name');

        if(empty($name) || mb_strlen($name)>20){

            return $this->error('商铺名称必须填写且长度不能多于10');

        }





        if(!$this->checkName($name)) return $this->error('商铺名称不能是纯数字或者包含测试两个字');



        if(null === $app= AppModel::find($app_id)){

            return $this->error('应用不存在');

        }

        if($app->is_delete!=0){

            return $this->error('应用不存在');

        }

        if($app->status==0){

            if(!in_array($this->request->accountId,$app->white_list)){

                return $this->error('您没有权限创建这个应用');

            }

        }



        $shop=new ShopModel();

        $shop->app_id=$app_id;

        $shop->name=$name;

        $shop->expire_time = $this->request->time() + 86400 * $app->trial_days;

        $shop->type = 2;

        $shop->save();



        //创建关系

        $shopAccount=new ShopAccountModel();

        $shopAccount->shop_id=$shop->shop_id;

        $shopAccount->account_id=$this->request->accountId;

        $shopAccount->save();



        //商铺初始化

        CreateShopLogic::create($shop->shop_id,$from_type);



        //生成授权链接

        $shop_token=TokenLogic::getShopToken($shop->shop_id,$this->request->accountId);

        $base_url=$app->status==1 ? $app->production_address : $app->development_address;



        $return=[

            'shop_token'=>$shop_token,

            'base_url'=>$base_url

        ];

        return $this->success($return);

    }



    protected function checkName($name)

    {

        if(is_numeric($name)) return false;

        if(strstr($name,'测试')) return false;

        return true;

    }

}

